<template>
    <AdminSkeleton>
        <template #header>
            <div class="params">
                <el-form :model="paramsForm" label-width="auto">
                    <el-form-item label="专业:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                            <el-select v-model="paramsForm.specialties" clearable placeholder="可留空" size="small"
                                style="width: 120px" multiple collapse-tags collapse-tags-tooltip
                                @visible-change="getSpecialties" @change="changeSpecialies">
                                <template #header>
                                    <el-checkbox v-model="specCheckAll" :indeterminate="specIndeterminate"
                                        @change="specHandleCheckAll">
                                        全选
                                    </el-checkbox>
                                </template>
                                <el-option v-for="item in specialtiesArr" :label="item.SPEC_DESC"
                                    :value="item.CUST_SPECNUM" :key="item.CUST_SPECNUM" />
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="getSubsys(paramsForm)"
                            :loading="loading">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>
        <template #control>
            <Control :batchIsShow="batchIsShow" :downloadBoxShow="downloadBoxShow" :permObj="permObj"
                @addClick="editSubsys('add', {})" @showDownload="showDownloadBox"
                @downloadExcelPaging="downloadExcelPaging(subsys, 'subsysTable', '子系统信息')"
                @downloadExcelAll="downloadExcelAll(subsys, '子系统信息')" @batchToggleShow="batchEdit"
                @batchDel="editSubmit('batchDel', selectSubsys)" @batchUpload="batchUpload">
            </Control>
        </template>
        <template #content>
            <el-table :data="subsys" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange"
                id="subsysTable">
                <el-table-column type="selection" width="50" v-if="selectShow" />
                <el-table-column prop="CUST_SUBSYS" label="子系统编码" width="100" />
                <el-table-column prop="SUBSYS" label="子系统" width="120" />
                <el-table-column prop="SUB_DESC" label="子系统描述" width="120" />
                <el-table-column prop="CUST_SPECNUM" label="专业" width="80" />
                <el-table-column prop="UNIT" label="单位" width="80" />
                <el-table-column fixed="right" label="Operations" min-width="120" v-perm="permObj.update">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" v-perm="permObj.update"
                            @click="editSubsys('update', row)" title="编辑">
                            <el-icon>
                                <Edit />
                            </el-icon>
                        </el-button>
                        <el-button type="warning" size="small" @click="editSubsys('copy', row)" title="复制"
                            v-perm="permObj.add">
                            <el-icon>
                                <CopyDocument />
                            </el-icon>
                        </el-button>
                        <el-button type="danger" size="small" class="del" title="删除" v-perm="permObj.delete"
                            @click="editSubmit('delete', row)">
                            <el-icon>
                                <DeleteFilled />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
    </AdminSkeleton>
    <Drawer ref="drawerRef" :title="title" :size="size" @submit="editSubmit(submitType, editForm)"
        @cancel-submit="resetForm">
        <el-form :model="editForm" ref="updateFormRef" :rules="rules">
            <el-form-item label="子系统编码" :label-width="formLabelWidth" prop="CUST_SUBSYS">
                <el-input v-model="editForm.CUST_SUBSYS" autocomplete="off" />
            </el-form-item>
            <el-form-item label="子系统" :label-width="formLabelWidth" prop="SUBSYS">
                <el-input v-model="editForm.SUBSYS" autocomplete="off" />
            </el-form-item>
            <el-form-item label="子系统描述" :label-width="formLabelWidth" prop="SUB_DESC">
                <el-input v-model="editForm.SUB_DESC" autocomplete="off" />
            </el-form-item>
            <el-form-item label="专业" :label-width="formLabelWidth" prop="CUST_SPECNUM"> 
                <el-select v-model="editForm.CUST_SPECNUM" 
                    placeholder="不可留空"                                                     
                >
                    <el-option v-for="item in specialtiesArr" :label="item.SPEC_DESC"
                        :value="item.CUST_SPECNUM" :key="item.CUST_SPECNUM" />
                </el-select>
            </el-form-item>
            <el-form-item label="单位" :label-width="formLabelWidth" prop="UNIT">
                <el-input v-model="editForm.UNIT" autocomplete="off" />
            </el-form-item>
        </el-form>
    </Drawer>
    <Dialog ref="dialogRef" :uploadKeys="uploadKeys" @uploadFile="uploadFile" @closeDialog="closeDialog"
        @batchUpdate="editSubmit('batchUpdate', uploadTable)" @batchAdd="editSubmit('batchAdd', uploadTable)"
        @downloadTemplate="downloadTemplate('upload-table', '子系统信息导入模板')">
        <el-table :data="uploadTable" style="width: 100%" ref="dialogTableRef" id="upload-table">
            <el-table-column prop="CUST_SUBSYS" label="子系统编码" width="100" />
            <el-table-column prop="SUBSYS" label="子系统" width="120" />
            <el-table-column prop="SUB_DESC" label="子系统描述" width="120" />
            <el-table-column prop="CUST_SPECNUM" label="专业" width="80" />
            <el-table-column prop="UNIT" label="单位" width="80" />            
        </el-table>
    </Dialog> 
</template>

<script setup>
import { ref, reactive } from 'vue'
import AdminSkeleton from '@/components/AdminSkeleton.vue'
import Control from '@/components/Control.vue'
import Drawer from '@/components/Drawer.vue'
import Dialog from '@/components/Dialog.vue'
import { getSubsysInfo,editSubsysInfo,batchEditSubsysInfo } from '@/utils/comminfoApi/subsys'
import { getSpecialtiesInfo } from '@/utils/xfjcApi/device'
import { xfjcStore } from '@/stores/jcStore'
import { msgOpen } from '@/utils/msg'
import { confirm, confirmBatch } from '@/utils/confirm'
import { exportClickFromTableId, exportClickFromDatas } from '@/utils/downloadExcel'
import { objCopy } from '@/utils/objCopy'

//权限对象--用于控制按钮显示
const permObj = {
    add: { name: 'Subsys', type: 'add' },
    update: { name: 'Subsys', type: 'update' },
    delete: { name: 'Subsys', type: 'delete' }
}

//实例化store
let useJcStore = xfjcStore()

//弹出层使用
let title = ref("")
let size = ref("35%")
let formLabelWidth = ref("80")

//区域信息查询
//#region 
//查询表单对象
let paramsForm = reactive({
    specialties: [],
})

//专业paramsForm
let specialtiesArr = ref([])
let specCheckAll = ref(false)
let specIndeterminate = ref(false)

//子系统信息（接收服务器响应后的数据）
let subsys = ref([])

//表格、查询按钮loading状态
let loading = ref(false)

/**
 * 获取专业
 */
const getSpecialties = async () => {
    if (!useJcStore.specialtiesInfo.length) {
        //获取专业
        let specRes = await getSpecialtiesInfo()
        if (specRes.status) {
            specialtiesArr.value = specRes.resDatas.specialties
            useJcStore.setSpecialtiesInfo(specialtiesArr.value)
        }
    } else {
        specialtiesArr.value = useJcStore.specialtiesInfo
    }
}

/**
 * 专业选择
 * @param val 专业数组
 */
const changeSpecialies = (val) => {
    if (Array.isArray(val)) {
        if (val.length === 1) {
            //取消全选
            if (specialtiesArr.value.length && val.length !== specialtiesArr.value.length) {
                specCheckAll.value = false
                specIndeterminate.value = true
            }
        }
        else if (val.length === 0) {
            specCheckAll.value = false
            specIndeterminate.value = false
        }
        else if (val.length > 1) {
            // 当val长度大于1切等于子系统数组长度时，全选勾选
            if (val.length === specialtiesArr.value.length) {
                specCheckAll.value = true
                specIndeterminate.value = false
            } else {
                specCheckAll.value = false
                specIndeterminate.value = true
            }
        }
    }
}

/**
 * 专业全选
 * @param val 专业全选值
 */
const specHandleCheckAll = (val) => {
    specIndeterminate.value = false
    if (val) {
        paramsForm.specialties = specialtiesArr.value.map((_) => _.value)
    } else {
        paramsForm.specialties = []
    }
}

const getSubsys = async () => {
    loading.value = true
    let res = await getSubsysInfo(paramsForm)
    subsys.value = res.resDatas.subsysInfo
    loading.value = false
    // console.log(res)
}

//#endregion

//批量处理
//#region 
let batchIsShow = ref(false) //展示批量上传、批量删除状态
let selectShow = ref(false) //展示批量勾选状态
let selectSubsys = ref([])
let dialogRef = ref(null) //组件ref
let uploadKeys = ref([
    "CUST_SUBSYS",
    "SUBSYS",
    "SUB_DESC",
    "CUST_SPECNUM",
    "UNIT",
])

const batchEdit = () => {
    if (subsys.value.length) selectShow.value = !selectShow.value
    batchIsShow.value = !batchIsShow.value
}
const handleSelectionChange = (val) => {
    selectSubsys.value = val
}

// //批量上传
let uploadTable = ref([])
const batchUpload = () => {
    // console.log('batchUpload');
    dialogRef.value.open()
}
//关闭
const closeDialog = () => {
    uploadTable = ref([])
    dialogRef.value.close()
}

//接收子组件传递的excel数据，渲染至界面
let dialogTableRef = ref(null)
const uploadFile = (e) => {
    uploadTable = e.value
}

// //下载
let downloadBoxShow = ref(false) //展示下载框状态
const showDownloadBox = () => {
    downloadBoxShow.value = !downloadBoxShow.value
}
/** 
 * 下载当前页
 * @param {Array} data 导出的数据数组对象
 * @param {String} tableId table标签的ID
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelPaging = (data, tableId, fileName) => {
    data.length ? exportClickFromTableId(tableId, fileName) : msgOpen("无数据可供下载，请先查询数据")
}
/**
 * 下载全部
 * @param {Array} data 导出的数据数组对象(未进行分页)
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelAll = (data, fileName) => {
    if (data.length) {
        let newData = JSON.parse(JSON.stringify(data)) //深拷贝
        for (let i = 0; i < newData.length; i++) {
            newData[i].PASSWORD ? newData[i].PASSWORD = "" : ""
        }
        // console.log(newData);        
        exportClickFromDatas(newData, fileName)
    } else {
        msgOpen("无数据可供下载，请先查询数据")
    }
}

/**
 * 导入模版下载
 * @param tableId table标签的ID
 * @param fileName 需要命名的文件名
 */
const downloadTemplate = (tableId, fileName) => {
    // console.log(tableId)
    exportClickFromTableId(tableId, fileName)
}
//#endregion

//编辑区域信息
//#region 
let drawerRef = ref(null) //组件ref
let oldSubsysInfo = reactive({
    CUST_SUBSYS: '',
    SUBSYS: '',
    SUB_DESC: '',
    CUST_SPECNUM: '',
    UNIT: '',
}) //用于存储未修改前用户信息
let editForm = reactive({
    CUST_SUBSYS: '',
    SUBSYS: '',
    SUB_DESC: '',
    CUST_SPECNUM: '',
    UNIT: '',
})
//编辑提交类型
let submitType = ref('')


// //表单验证ref
let updateFormRef = ref(null)
//输入框验证规则
let rules = reactive({
    CUST_SUBSYS: [
        { required: true, message: '请输入子系统编码', trigger: 'blur' },
    ],
    SUBSYS: [
        { required: true, message: '请输入子系统名称', trigger: 'blur' },
    ],
    SUB_DESC: [
        { required: true, message: '请输入子系统描述', trigger: 'blur' },
    ],
    CUST_SPECNUM: [
        { required: true, message: '请输入专业编码', trigger: 'blur' },
    ],
    // UNIT: [
    //     { required: true, message: '请输入单位', trigger: 'blur' },
    // ],
})

// //重置表单
const resetForm = () => {
    if (submitType.value === 'update') {
        editForm = objCopy(oldSubsysInfo, editForm)
    } else if (submitType.value === 'add') {
        editForm = reactive({
            CUST_SUBSYS: '',
            SUBSYS: '',
            SUB_DESC: '',
            CUST_SPECNUM: '',
            UNIT: '',
        })
    }
}

/**
 * @param {String} type 处理类型
 * @param {Object} row 行对象
 */
const editSubsys = (type, row) => {
    submitType.value = type
    drawerRef.value.open()
    if (type === 'update') {
        title.value = "编辑"
        editForm = row
        oldSubsysInfo = objCopy(row, oldSubsysInfo) //存储未修改前用户信息 
        // console.log(oldUserInfo);                
    }
    if (type === 'add') {
        title.value = "新增"
        resetForm()
    }
    if (type === 'copy') {
        title.value = "复制"
        editForm = objCopy(row, editForm)
        editForm.CUST_SUBSYS += "_副本"
    }
    // console.log(row);    
}
//#endregion

/**
 * 编辑提交
 * @param type 操作类型
 * @param data 操作数据
 */
const editSubmit = async (type, data) => {
    console.log(type, data)
    if(type === 'update' || type === 'add' || type === 'copy'){
        updateFormRef.value.validate(async (valid)=>{
            if(!valid){
                return false
            }else{              
                drawerRef.value.showLoading()
                let newSubsys = await editSubsysInfo(type,data)
                // console.log(newSubsys)
                drawerRef.value.hideLoading()
                drawerRef.value.close()
                newSubsys.status ? msgOpen(newSubsys.msg,'success') : msgOpen(newSubsys.msg) 
                getSubsys(paramsForm)              
            }
        })
    }
    if(type === 'delete'){
        let res = await confirm(data.SUBSYS)       
        if(res){
            let newSubsys = await editSubsysInfo(type,data)
            // console.log(newUser);
            msgOpen(newSubsys.msg,'success')
            getSubsys(paramsForm) 
        }  
    }
    if(type === 'batchUpdate' || type === 'batchAdd'){
        let rowsArr = ref([]) 
        let editBatchStatus = ref(true)
        for(let i = 0;i < data.length;i++){
            // console.log(data[i]);            
            if(!data[i].CUST_SUBSYS.length){
                msgOpen(`第${i + 1 }行错误，请填写CUST_SUBSYS值！`)
                editBatchStatus.value = false
                break
            }else{
                rowsArr.value.push(data[i])
            }
        }
        if(editBatchStatus.value){
            let newSubsys = await batchEditSubsysInfo(type,data)  
            // console.log(newSubsys)
            dialogRef.value.close()
            uploadTable = ref([])
            if(!newSubsys.status){
                msgOpen(newSubsys.msg)
            }else{
                newSubsys.resDatas.newSubsys.rowsAffected ? msgOpen(`${newSubsys.msg},共${newSubsys.resDatas.newSubsys.rowsAffected}条`,"success") 
                                                            : msgOpen(newSubsys.msg)
            }        
            getSubsys(paramsForm)   
        }
    }
    if(type === 'batchDel'){
        if(!data.length){
            msgOpen('未进行勾选，请勾选！')
        }else{
            let isDel = await confirmBatch(data.length) 
            if(isDel){
                let subsysArr = []
                data?.forEach(item => {
                    let arr = []
                    arr.push(item.CUST_SUBSYS) 
                    subsysArr.push(arr)
                })
                let newSubsys = await batchEditSubsysInfo(type,subsysArr) 
                if(!newSubsys.status){
                    msgOpen(newSubsys.msg)
                }else{
                    newSubsys.resDatas.newSubsys.rowsAffected ? msgOpen(`${newSubsys.msg},共${newSubsys.resDatas.newSubsys.rowsAffected}条`,"success") 
                                                                : msgOpen(newSubsys.msg)
                }        
                getSubsys(paramsForm) 
            }
        }
    }
}

</script>

<style lang="less" scoped>
.params {
    width: 100%;
    height: 100%;

    .el-form {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;

        .el-form-item {
            margin-bottom: 0;
            margin-right: .3125rem;
        }
    }

}

.el-table {
    height: 95%;
}
</style>